package com.sentinel.demo01.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 这里通过拦截器 统一做处理
 *
 * @author lihh
 */
@Slf4j
@Component
public class CustomBlockExceptionHandler implements BlockExceptionHandler {
  @Override
  public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
    log.info("custom common block exception");
    
    // 尝试从 request 拿到参数
    Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
      log.info("params {} = {}", entry.getKey(), entry.getValue());
    }
    
    String rs = null;
    
    if (e instanceof FlowException)
      rs = "接口被限流了";
    else if (e instanceof DegradeException)
      rs = "服务被降级了";
    else if (e instanceof ParamFlowException)
      rs = "热点参数限流了";
    else if (e instanceof SystemBlockException)
      rs = "触发系统保护规则了";
    else if (e instanceof AuthorityException)
      rs = "授权规则不通过";
    
    // 这里返回 json 数据
    httpServletResponse.setStatus(500);
    httpServletResponse.setCharacterEncoding("utf-8");
    httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
    new ObjectMapper().writeValue(httpServletResponse.getWriter(), rs);
  }
}
